package com.yuke.cloud.service.omc.controller.frontend;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.omc.dto.OrderBasicDto;
import com.yuke.cloud.service.omc.dto.OrderGoodsDto;
import com.yuke.cloud.service.omc.dto.ShopOrderGoodsDto;
import com.yuke.cloud.service.omc.entity.OdsOrder;
import com.yuke.cloud.service.omc.entity.OdsOrderGoods;
import com.yuke.cloud.service.omc.service.OdsOrderGoodsService;
import com.yuke.cloud.service.omc.service.OdsOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by ssx on 2018/09/04.
 */
@Api(value = "WEB - OdsOrderGoodsController", tags = "处理OdsOrderGoods相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("ods/order_goods")
@Slf4j
public class OdsOrderGoodsController extends BaseController {
    @Resource
    private OdsOrderGoodsService odsOrderGoodsService;
    @Resource
    private OdsOrderService odsOrderService;
    @Autowired
    private PmcFeignApi pmcFeignApi;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Autowired
    private WmcStorageFeignApi wmcStorageFeignApi;



    //统计当周销售-额
    @GetMapping("/getnumbyweek/{id}")
    public Wrapper getnumbyweek(@ApiParam(name = "id", value = "店铺id") @PathVariable Long id) {
        //获取本周的第一天
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date date = cal.getTime();

        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThanOrEqualTo("payTime", new Date());
        criteria.andGreaterThanOrEqualTo("payTime", date);
        criteria.andEqualTo("shopId", id);
        criteria.andEqualTo("orderType", 1);
        criteria.andEqualTo("payStatus", 1);  // add by wg 20190328
        List<OdsOrder> list = odsOrderService.selectByExample(example);
        if (list.size() == 0) {
            Map map = new HashMap();
            map.put("weeksales", 0);
            map.put("daysales", 0);
        }
        int weekmoney = 0;
        for (int i = 0; i < list.size(); i++) {
            OdsOrder odsOrder = list.get(i);
            if (odsOrder.getOrderStatus().toString().equals("4")) {
                // mod by wg 20190328 对于退货最好也获取退款信息后再处理
//                weekmoney = weekmoney + 0;
                int refundmoney = wmcStorageFeignApi.assessinfo(odsOrder.getOrderId());
                weekmoney = weekmoney + odsOrder.getAmountPaid() - refundmoney;
            } else if (odsOrder.getOrderStatus().toString().equals("5")) {
                int refundmoney = wmcStorageFeignApi.assessinfo(odsOrder.getOrderId());
                weekmoney = weekmoney + odsOrder.getAmountPaid() - refundmoney;
            } else {
                weekmoney = weekmoney + list.get(i).getAmountPaid();
            }

            weekmoney -= list.get(i).getFreightPayable();  // add by wg 20190328 减去运费
        }


        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(new Date());
        calendar1.set(Calendar.HOUR_OF_DAY, 0);
        calendar1.set(Calendar.MINUTE, 0);
        calendar1.set(Calendar.SECOND, 0);
        Date time = calendar1.getTime();
        Example example1 = new Example(OdsOrder.class);
        Example.Criteria criteria2 = example1.createCriteria();
        criteria2.andLessThanOrEqualTo("payTime", new Date());
        criteria2.andGreaterThanOrEqualTo("payTime", time);
        criteria2.andEqualTo("shopId", id);
        criteria2.andEqualTo("orderType", 1);
        criteria2.andEqualTo("payStatus", 1);  // add by wg 20190328
        List<OdsOrder> list2 = odsOrderService.selectByExample(example1);
        if (list2.size() == 0) {
            Map map = new HashMap();
            map.put("weeksales", 0);
            map.put("daysales", 0);
        }
        int daysales = 0;
        for (int i = 0; i < list2.size(); i++) {
            if (list2.get(i).getOrderStatus().toString().equals("4")) {
                // mod by wg 20190328 对于退货最好也获取退款信息后再处理
//                daysales = daysales + 0;
                int refundmoney1 = wmcStorageFeignApi.assessinfo(list2.get(i).getOrderId());
                daysales = daysales + list2.get(i).getAmountPaid() - refundmoney1;
            } else if (list2.get(i).getOrderStatus().toString().equals("5")) {
                int refundmoney1 = wmcStorageFeignApi.assessinfo(list2.get(i).getOrderId());
                daysales = daysales + list2.get(i).getAmountPaid() - refundmoney1;
            } else {
                daysales = daysales + list2.get(i).getAmountPaid();
            }
            daysales -= list2.get(i).getFreightPayable();  // add by wg 20190328 减去运费

        }
        Map map = new HashMap();
        map.put("weeksales", weekmoney);
        map.put("daysales", daysales);
        return WrapMapper.ok(map);
    }

    //统计某个时间段销售额-额
    @GetMapping("/getsalesbytime")
    public Wrapper getsalesbytime(@RequestParam("begintime") Date begintime,
                                  @RequestParam("endtime") Date endtime,
                                  @RequestParam("id") Long id) {
        List<Map> list = odsOrderService.countsalesbytime(begintime, endtime, id);
        Calendar instance1 = Calendar.getInstance();
        instance1.setTime(begintime);
        Calendar instance2 = Calendar.getInstance();
        instance2.setTime(endtime);
        long difference = (endtime.getTime() - begintime.getTime()) / 86400000;
        long abs = Math.abs(difference);
        List<Map> list1 = new ArrayList<>();
        for (int i = 0; i <= abs; i++) {
            int year = instance1.get(Calendar.YEAR);
            int month = instance1.get(Calendar.MONTH) + 1;
            int day = instance1.get(Calendar.DAY_OF_MONTH);
            instance1.add(Calendar.DAY_OF_MONTH, 1);
            boolean flag = false;
            for (int j = 0; j < list.size(); j++) {
                Map map = list.get(j);
                String nian = map.get("nian").toString();
                String yue = map.get("yue").toString();
                String ri = map.get("ri").toString();
                int money = Integer.parseInt(map.get("money").toString());
                if (map.get("refund_paid") != null) {
                    int refund_paid = Integer.parseInt(map.get("refund_paid").toString());
                    money = money - refund_paid;
                }
                // add by wg 20190328 增加去掉运费
                if (map.get("freight_payable") != null) {
                    int freight_payable = Integer.parseInt(map.get("freight_payable").toString());
                    money = money - freight_payable;
                }
                if (nian.equals(year + "") && yue.equals(month + "") && ri.equals(day + "")) {
                    Map map1 = new HashMap();
                    map1.put("year", year);
                    map1.put("month", month);
                    map1.put("day", day);
                    map1.put("thing", money);
                    list1.add(map1);
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                Map map1 = new HashMap();
                map1.put("year", year);
                map1.put("month", month);
                map1.put("day", day);
                map1.put("thing", 0);
                list1.add(map1);

            }

        }

        return WrapMapper.ok(list1);
    }

    //统计某个时间段销售量-量
    @GetMapping("/getnumbytime")
    public Wrapper getnumbytime(@ApiParam(name = "begintime", value = "店铺id") Date begintime,
                                @ApiParam(name = "endtime", value = "店铺id") Date endtime,
                                @ApiParam(name = "id", value = "店铺id") Long id) {
        List<Map> list = odsOrderService.countnumbytime(begintime, endtime, id);
        Calendar instance1 = Calendar.getInstance();
        instance1.setTime(begintime);
        Calendar instance2 = Calendar.getInstance();
        instance2.setTime(endtime);
        long difference = (endtime.getTime() - begintime.getTime()) / 86400000;
        long abs = Math.abs(difference);
        List<Map> list1 = new ArrayList<>();

        for (int i = 0; i <= abs; i++) {
            int year = instance1.get(Calendar.YEAR);
            int month = instance1.get(Calendar.MONTH) + 1;
            int day = instance1.get(Calendar.DAY_OF_MONTH);
            instance1.add(Calendar.DAY_OF_MONTH, 1);
            boolean flag = false;
            for (int j = 0; j < list.size(); j++) {
                Map map = list.get(j);
                String nian = map.get("nian").toString();
                String yue = map.get("yue").toString();
                String ri = map.get("ri").toString();
                String nums = map.get("nums").toString();

                if (nian.equals(year + "") && yue.equals(month + "") && ri.equals(day + "")) {
                    Map map1 = new HashMap();
                    map1.put("year", year);
                    map1.put("month", month);
                    map1.put("day", day);
                    map1.put("thing", nums);
                    list1.add(map1);
                    flag = true;
                    break;
                }

            }
            if (!flag) {
                Map map1 = new HashMap();
                map1.put("year", year);
                map1.put("month", month);
                map1.put("day", day);
                map1.put("thing", 0);
                list1.add(map1);

            }

        }


        return WrapMapper.ok(list1);
    }


    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "odsOrderGoods", value = "该数据记录的POJO") @RequestBody OdsOrderGoods odsOrderGoods) {
        odsOrderGoodsService.save(odsOrderGoods);
        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        odsOrderGoodsService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "odsOrderGoods", value = "需要修改的内容") @RequestBody OdsOrderGoods odsOrderGoods) {
        odsOrderGoodsService.update(odsOrderGoods);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<OdsOrderGoods> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        OdsOrderGoods odsOrderGoods = odsOrderGoodsService.findById(id);
        return WrapMapper.ok(odsOrderGoods);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<OdsOrderGoods>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                 @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<OdsOrderGoods> list = odsOrderGoodsService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }


    //商店查询自己店铺下面用户的订单
    @GetMapping("/getbytype")
    @ApiOperation(httpMethod = "GET", value = "分页获订单状态记录（全部，已付款，未付款，已取消，未取消,已退货）有记录")
    public Wrapper<PageInfo<OdsOrder>> list1(
            @ApiParam(name = "shopid", value = "查询条件(全部，已付款，未付款，已取消，未取消,已退货)", defaultValue = "0") @RequestParam Long shopid,
            @ApiParam(name = "type", value = "查询条件(全部，已付款，未付款，已取消，未取消,已退货)", defaultValue = "0") @RequestParam String type,
            @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size
    ) throws ParseException {


        // add by wg 20190517 增加待发货处理订单，仅针对云顶店铺的即时达订单及厂家直销订单
        if (type.equals("needtosend")) {
            // 对于云顶店铺，如果订单配送方式为即时达，则需要店铺确认是自己配送还是交由平台配送
            // 获取店铺信息
            List<ShopInfoDto> shopInfoDtos = smcFeignApi.getShopInfoByShopIds(Collections.singletonList(shopid));
            if (shopInfoDtos == null && shopInfoDtos.size() == 0) {
                log.error("调用smcFeignApi.getShopInfoByShopIds没有结果返回");
                return WrapMapper.error("无法获取店铺信息");
            }

            OdsOrder odsOrder = new OdsOrder();
            if (shopInfoDtos.get(0).getShopType() == 1) {  // 云顶店铺
                odsOrder.setShippingType((byte) 0); // 即时达(还未确定谁配送)
                odsOrder.setShopId(shopid);
            } else if (shopInfoDtos.get(0).getShopType() == 3) {
                odsOrder.setFactoryShopId(shopid);
            } else {
                List<OdsOrder> tempList = new ArrayList<>();
                PageInfo pageInfo = new PageInfo(tempList);
                pageInfo.setList(tempList);
                return WrapMapper.ok(pageInfo);
            }

            odsOrder.setOrderType((byte) 1);
            odsOrder.setPayStatus((byte)1);
            odsOrder.setShippingStatus((byte)0);

            PageHelper.startPage(page, size);

            List<OdsOrder> odsOrders = odsOrderService.findbystatus(odsOrder);
            PageInfo pageInfo = new PageInfo(odsOrders);
            if (odsOrders.size() == 0) {
                return WrapMapper.ok(pageInfo);
            }

            List<Long> OrderIds = new ArrayList<>();
            for (OdsOrder odsOrderTemp : odsOrders) {
                if (odsOrderTemp.getOrderId() != null) {
                    OrderIds.add(odsOrderTemp.getOrderId());
                }
            }

            PageHelper.startPage(0, 0);  // 恢复

            List<Map> orderGoods = odsOrderService.getgoods(OrderIds);
            String specIds = formatit(orderGoods);
            //sbfrign
            List<ProdSpecInfoDto> prodSpecInfoDtos = pmcFeignApi.getSpecInfoDtosBySpecIds(specIds);
            if (prodSpecInfoDtos == null || prodSpecInfoDtos.size() == 0) {
                List<OdsOrder> tempList = new ArrayList<>();
                pageInfo.setList(tempList);
                return WrapMapper.ok(pageInfo);
            }
            List<OdsOrder> odsOrdersResult = formatit2(prodSpecInfoDtos, orderGoods);
            pageInfo.setList(odsOrdersResult);

            return WrapMapper.ok(pageInfo);
        }

        //待处理(1订单生成成功，未确认，也就是未确认已支付，需要商家确认然后发货2用户申请退款需要店铺确认)
        if (type.equals("needtodo")) {
            System.out.println("进入");
            Map map = new HashMap();
            map.put("orderType", 1);
            map.put("returnStatus", 5);
            map.put("shopId", shopid);
            // add by wg 20190403 增加分页查询
            map.put("page", page);
            map.put("size", size);
            // 待退款、退货处理
            Wrapper getassreturnWrap = wmcStorageFeignApi.getassreturn(map);
            if (getassreturnWrap == null) {
                List<OdsOrder> tempList = new ArrayList<>();
                PageInfo pageInfo = new PageInfo(tempList);
                return WrapMapper.ok(pageInfo);
            }
            PageInfo pageInfo = (PageInfo)getassreturnWrap.getResult();
            List<Map> getassreturn = (List<Map>)pageInfo.getList();
            if (getassreturn == null || getassreturn.size() == 0) {
//                return WrapMapper.ok("");
                List<OdsOrder> tempList = new ArrayList<>();
                pageInfo.setList(tempList);
                return WrapMapper.ok(pageInfo);
            }
            List<Long> list = new ArrayList<>();
            for (int i = 0; i < getassreturn.size(); i++) {
                if (!getassreturn.get(i).get("orderId").toString().equals("")) {
                    list.add(Long.valueOf(getassreturn.get(i).get("orderId").toString()));
                }

            }
            //用户付款不需要确认
            /*Example example2 = new Example(OdsOrder.class);
            example2.setOrderByClause("create_time desc");
            Example.Criteria criteria2 = example.createCriteria();
            criteria2.andEqualTo("orderType", 1);
            criteria2.andEqualTo("orderStatus", 0);
            criteria2.andEqualTo("pay_status", 1);
            criteria2.andEqualTo("shopId", shopid);
            List<OdsOrder> list6 = odsOrderService.selectByExample(example2);
            for (int i = 0; i < list6.size(); i++) {
                list1.add(list6.get(i).getOrderId());
            }*/
            System.err.println(list);
            List<Map> list3 = odsOrderService.getgoods(list);
            String formatit = formatit(list3);
            //todo 调用feign,
            List<ProdSpecInfoDto> specInfoDtosBySpecIds = pmcFeignApi.getSpecInfoDtosBySpecIds(formatit);
            if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
//                return WrapMapper.ok("");
                List<OdsOrder> tempList = new ArrayList<>();
                pageInfo.setList(tempList);
                return WrapMapper.ok(pageInfo);
            }
            List<OdsOrder> list8 = formatit2(specInfoDtosBySpecIds, list3);
            for (int i = 0; i < list8.size(); i++) {
                for (int j = 0; j < getassreturn.size(); j++) {
                    if (list8.get(i).getOrderId().toString().equals(getassreturn.get(j).get("orderId").toString())) {
                        list8.get(i).setReturnId(Long.valueOf(getassreturn.get(j).get("goodsReturnId").toString()));
                    }
                }
            }

//            return WrapMapper.ok(list8);
            pageInfo.setList(list8);
            return WrapMapper.ok(pageInfo);
        }
        //在途中,配送中
        if (type.equals("onroute")) {
            OdsOrder ods = new OdsOrder();
            ods.setShippingStatus((byte) 2);
            ods.setOrderType((byte) 1);
            ods.setShopId(shopid);  // add by wg 20190320

            PageHelper.startPage(page, size);

            List<OdsOrder> list = odsOrderService.findbystatus(ods);
            PageInfo pageInfo = new PageInfo(list);
            if (list.size() == 0) {
//                return WrapMapper.ok("");
                return WrapMapper.ok(pageInfo);
            }


            List<Long> list2 = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getOrderId() != null && !list.get(i).getOrderId().toString().equals("")) {
                    list2.add(list.get(i).getOrderId());
                }

            }

            PageHelper.startPage(0, 0);  // 恢复

            List<Map> list3 = odsOrderService.getgoods(list2);
            String formatit = formatit(list3);
            //sbfrign
            List<ProdSpecInfoDto> specInfoDtosBySpecIds = pmcFeignApi.getSpecInfoDtosBySpecIds(formatit);
            if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
//                return WrapMapper.ok("");

                List<OdsOrder> tempList = new ArrayList<>();
                pageInfo.setList(tempList);
                return WrapMapper.ok(pageInfo);
            }
            List<OdsOrder> list8 = formatit2(specInfoDtosBySpecIds, list3);
//            return WrapMapper.ok(list8);
            pageInfo.setList(list8);

            return WrapMapper.ok(pageInfo);
        }
        //已完成
        if (type.equals("finished")) {
            Map map = new HashMap();
            map.put("orderType", 1);
            map.put("returnStatus", 5);  // 退货申请待确认
            map.put("shopId", shopid);
            map.put("page", 0);
            map.put("size", 0);
            Wrapper getassreturnWrap = wmcStorageFeignApi.getassreturn(map);
            if (getassreturnWrap == null) {
                List<OdsOrder> tempList = new ArrayList<>();
                PageInfo pageInfo = new PageInfo(tempList);
                return WrapMapper.ok(pageInfo);
            }
            PageInfo pageInfo = (PageInfo)getassreturnWrap.getResult();
            List<Map> list4 = (List<Map>)pageInfo.getList();
//            List<Map> list4 = wmcStorageFeignApi.getassreturn(map);
            System.out.println(list4);
            if (list4 == null) {
//                return WrapMapper.ok("");
                List<OdsOrder> tempList = new ArrayList<>();
                pageInfo.setList(tempList);
                return WrapMapper.ok(pageInfo);
            }
            Example example2 = new Example(OdsOrder.class);
            example2.setOrderByClause("create_time desc");
            Example.Criteria criteria2 = example2.createCriteria();
            criteria2.andEqualTo("shopId", shopid);
            criteria2.andEqualTo("orderType", 1);
            // add by wg 20190326 只有订单状态是
            List<Byte> listStatus = new ArrayList<>();
            listStatus.add((byte)2);
            listStatus.add((byte)3);
            listStatus.add((byte)4);
            listStatus.add((byte)5);
            listStatus.add((byte)6);
            criteria2.andIn("orderStatus", listStatus); // add by wg 20190326 只有订单状态是
            if (list4.size() == 0) {
            } else {
                List<Long> getassreturn = new ArrayList<>();
                for (int i = 0; i < list4.size(); i++) {
                    getassreturn.add(Long.valueOf(list4.get(i).get("orderId").toString()));
                }
                criteria2.andNotIn("orderId", getassreturn);
            }

            // add by wg 20190403 增加分页查询
            PageHelper.startPage(page, size);
            List<OdsOrder> list1 = odsOrderService.selectByExample(example2);
            pageInfo = new PageInfo(list1);
            if (list1.size() == 0) {
//                return WrapMapper.ok("");
                return WrapMapper.ok(pageInfo);
            }
            List<Long> list5 = new ArrayList<>();
            for (int i = 0; i < list1.size(); i++) {
                if (list1.get(i).getOrderId() != null && !list1.get(i).getOrderId().toString().equals("")) {
                    list5.add(list1.get(i).getOrderId());
                }
            }

            PageHelper.startPage(0, 0);  // 恢复
            List<Map> list3 = odsOrderService.getgoods(list5);
            //1已确认交由仓库发货2同意退货完成的
            String sb = formatit(list3);
            List<ProdSpecInfoDto> specInfoDtosBySpecIds = pmcFeignApi.getSpecInfoDtosBySpecIds(sb);
            if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
//                return WrapMapper.ok("");
                List<OdsOrder> tempList = new ArrayList<>();
                pageInfo.setList(tempList);
                return WrapMapper.ok(pageInfo);
            }
            List<OdsOrder> list8 = formatit2(specInfoDtosBySpecIds, list3);
            /*for (int i = 0; i < list4.size(); i++) {
                for (int j = 0; j < list8.size(); j++) {
                    if (list4.get(i).get("orderId").toString().equals(list8.get(j).getOrderId().toString())) {
                        list8.get(j).setReturnStatus(list4.get(i).get("returnStatus").toString());
                    }
                }
            }*/
//            return WrapMapper.ok(list8);
            pageInfo.setList(list8);
            return WrapMapper.ok(pageInfo);
        }
        //已完成
        if (type.equals("confirmed")) {


        }
        //已取消
        if (type.equals("cancelled")) {
            OdsOrder ods = new OdsOrder();
            ods.setOrderStatus((byte) 3);
            ods.setShopId(Long.valueOf(shopid));
            //list = odsOrderService.findbystatus(ods);
        }
        //已退货，退款
        if (type.equals("refund")) {
            OdsOrder ods = new OdsOrder();
            ods.setOrderStatus((byte) 4);
            ods.setShopId(Long.valueOf(shopid));
            //list = odsOrderService.findbystatus(ods);
        }

//        return WrapMapper.ok();
        List<OdsOrder> tempList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo(tempList);
        return WrapMapper.ok(pageInfo);
    }

    private List<OdsOrder> formatit2(List<ProdSpecInfoDto> specInfoDtosBySpecIds, List<Map> list3) throws ParseException {
        List<OdsOrder> list8 = new ArrayList<>();
        Set<String> set = new HashSet();
        for (int i = 0; i < list3.size(); i++) {
            set.add(list3.get(i).get("order_id").toString());
        }

        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            OdsOrder odsOrder = new OdsOrder();
            List<OdsOrderGoods> list = new ArrayList<>();
            for (int i = 0; i < list3.size(); i++) {
                if (list3.get(i).get("order_id").toString().equals(next)) {
                    Map map = list3.get(i);
                    // mod by wg 20190410
//                    SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
//                    Date create_time = sf.parse(map.get("create_time").toString());
                    Date create_time = (Date)map.get("create_time");
                    odsOrder.setCreateTime(create_time);
                    Integer order_status = Integer.valueOf(map.get("order_status").toString());
                    odsOrder.setOrderStatus((byte) order_status.intValue());
                    // add by wg 20190326
                    Integer pay_status = Integer.valueOf(map.get("pay_status").toString());
                    odsOrder.setPayStatus((byte) pay_status.intValue());

                    odsOrder.setConsignee(map.get("consignee").toString());
                    odsOrder.setUserId(Long.valueOf(map.get("user_id").toString()));

                    odsOrder.setFreightPayable(Integer.valueOf(map.get("freight_payable").toString()));
                    odsOrder.setAddress(map.get("address").toString());
                    odsOrder.setTelephone(map.get("telephone").toString());
                    odsOrder.setOrderId(Long.valueOf(map.get("order_id").toString()));
                    odsOrder.setAmountPayable(Integer.valueOf(map.get("amount_payable").toString()));
                    OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                    odsOrderGoods.setPrice(Integer.valueOf(map.get("goods_price").toString()));
                    odsOrderGoods.setSpecId(Long.valueOf(map.get("spec_id").toString()));
                    odsOrderGoods.setGoodsNum(Integer.valueOf(map.get("goods_num").toString()));
                    if (specInfoDtosBySpecIds != null) {
                        for (int j = 0; j < specInfoDtosBySpecIds.size(); j++) {
                            if (map.get("spec_id").toString().equals(specInfoDtosBySpecIds.get(j).getSpecId().toString())) {
                                odsOrderGoods.setImagesAddress(specInfoDtosBySpecIds.get(j).getPicture());
                                odsOrderGoods.setSpecName(specInfoDtosBySpecIds.get(j).getSpecName());
                                //odsOrderGoods.setPayPrice(specInfoDtosBySpecIds.get(j).getStockPrice());
                            }
                        }
                    }


                    list.add(odsOrderGoods);
                }
            }
            odsOrder.setOdsgoods(list);
            list8.add(odsOrder);
        }
        return list8;
    }

    private String formatit(List<Map> list3) {
        StringBuilder stringBuilder = new StringBuilder();
        if (list3.size() == 0) {
            return "";
        } else {
            for (int i = 0; i < list3.size(); i++) {
                String spec_id = list3.get(i).get("spec_id").toString();
                if (i == list3.size() - 1) {
                    stringBuilder.append(spec_id);
                } else {
                    stringBuilder.append(spec_id).append(",");
                }

            }
            return stringBuilder.toString();
        }

    }

    //店铺查看自己的订单
    @PostMapping("/getorder")
    @ApiOperation(httpMethod = "POST", value = "分页获订单状态记录（全部，已付款，未付款，未评价）有记录")
    public Wrapper<PageInfo<OdsOrder>> list(@RequestBody JSONObject jsonObject,
                                        @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                        @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        String shopid = jsonObject.get("shopid").toString();
        String condition = jsonObject.get("condition").toString();
        List<OdsOrder> list = null;
        List<OdsOrder> odsOrders = new ArrayList<>();

        //查询所有
        if (condition.equals("all")) {
            OdsOrder ods = new OdsOrder();
            ods.setShopId(Long.valueOf(shopid));
            ods.setOrderType((byte) 2);
            ods.setPayStatus((byte)1); // add by wg 20190322 对于店铺进货单，只查看已经支付的
            PageHelper.startPage(page, size); // add by wg 20190403 增加分页查询
            list = odsOrderService.findbystatus(ods);
            PageInfo pageInfo = new PageInfo(list);

            List<OdsOrder> list1 = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                // mod by wg 20190322 对于店铺进货单，只查看已经支付的
//                if (list.get(i).getOrderStatus().intValue() == 0 && list.get(i).getPayStatus().intValue() == 0) {
                if (list.get(i).getPayStatus().intValue() == 0) {
                } else {
                    list1.add(list.get(i));
                }
            }

            PageHelper.startPage(0, 0); // add by wg 20190403 恢复

            for (int i = 0; i < list1.size(); i++) {
                OdsOrder odsOrder = list1.get(i);
                OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                odsOrderGoods.setOrderId(odsOrder.getOrderId());
                List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
                odsOrder.setOdsgoods(select);
                odsOrders.add(odsOrder);
            }

//            return WrapMapper.ok(odsOrders);
            pageInfo.setList(odsOrders);
            return WrapMapper.ok(pageInfo);
        }
        //待收货
        if (condition.equals("needaccept")) {
            OdsOrder ods = new OdsOrder();
            ods.setPayStatus((byte) 1);
            ods.setOrderStatus((byte) 1);
            ods.setShippingStatus((byte) 2);
            ods.setShopId(Long.valueOf(shopid));
            ods.setOrderType((byte) 2);
            PageHelper.startPage(page, size); // add by wg 20190403 增加分页查询
            list = odsOrderService.findbystatus(ods);
            PageInfo pageInfo = new PageInfo(list);

            PageHelper.startPage(0, 0); // add by wg 20190403 恢复
            for (int i = 0; i < list.size(); i++) {
                OdsOrder odsOrder = list.get(i);
                OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                odsOrderGoods.setOrderId(odsOrder.getOrderId());
                List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
                odsOrder.setOdsgoods(select);
                odsOrders.add(odsOrder);
            }
//            return WrapMapper.ok(odsOrders);
            pageInfo.setList(odsOrders);
            return WrapMapper.ok(pageInfo);
        }
        //待支付
        if (condition.equals("needpay")) {
            OdsOrder ods = new OdsOrder();
            ods.setOrderStatus((byte) 0);
            ods.setPayStatus((byte) 0);
            ods.setShopId(Long.valueOf(shopid));
            ods.setOrderType((byte) 2);
            PageHelper.startPage(page, size); // add by wg 20190403 增加分页查询
            list = odsOrderService.findbystatus(ods);
            PageInfo pageInfo = new PageInfo(list);
            PageHelper.startPage(0, 0); // add by wg 20190403 恢复
            for (int i = 0; i < list.size(); i++) {
                OdsOrder odsOrder = list.get(i);
                OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                odsOrderGoods.setOrderId(odsOrder.getOrderId());
                List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
                odsOrder.setOdsgoods(select);
                odsOrders.add(odsOrder);
            }
//            return WrapMapper.ok(odsOrders);
            pageInfo.setList(odsOrders);
            return WrapMapper.ok(pageInfo);
        }
        //退款售后
     /*   if (condition.equals("aftersales")) {
            OdsOrder ods = new OdsOrder();
            ods.setShippingStatus((byte) 3);
            ods.setShopId(Long.valueOf(shopid));
            ods.setOrderType((byte) 2);
            list = odsOrderService.findbystatus(ods);
            for (int i = 0; i < list.size(); i++) {
                OdsOrder odsOrder = list.get(i);
                OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                odsOrderGoods.setOrderId(odsOrder.getOrderId());
                List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
                odsOrder.setOdsgoods(select);
                odsOrders.add(odsOrder);
            }

        }*/
        if (condition.equals("refund")) {

            Map map = new HashMap();
            map.put("orderType", 2);
            map.put("shopId", shopid);

            // add by wg 20190403 增加分页查询
            map.put("page", page);
            map.put("size", size);
            Wrapper getassreturnWrap = wmcStorageFeignApi.getassreturn3(map);
            if (getassreturnWrap == null) {
                List<OdsOrder> tempList = new ArrayList<>();
                PageInfo pageInfo = new PageInfo(tempList);
                return WrapMapper.ok(pageInfo);
            }
            PageInfo pageInfo = (PageInfo)getassreturnWrap.getResult();
            List<Map> list1 = (List<Map>)pageInfo.getList();
//            List<Map> list1 = wmcStorageFeignApi.getassreturn3(map);
            if (list1 == null || list1.size() == 0) {
                List<OdsOrder> odsOrders5 = new ArrayList<>();

//                return WrapMapper.ok(odsOrders5);
                pageInfo = new PageInfo(odsOrders5);
                return WrapMapper.ok(pageInfo);
            }
            List<Long> getassreturn = new ArrayList<>();
            for (int i = 0; i < list1.size(); i++) {
                getassreturn.add(Long.valueOf(list1.get(i).get("orderId").toString()));
            }
            Example example1 = new Example(OdsOrder.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andIn("orderId", getassreturn);
            list = odsOrderService.selectByExample(example1);
            for (int i = 0; i < list1.size(); i++) {
                for (int j = 0; j < list.size(); j++) {
                    if (list1.get(i).get("orderId").toString().equals(list.get(j).getOrderId().toString())) {
                        list.get(j).setReturnStatus(list1.get(i).get("returnStatus").toString());
                        if (list1.get(i).get("returnStatus").toString().equals("3")) {
                            list.get(j).setRefuseReason("质检不通过");
                        } else if (list1.get(i).get("returnStatus").toString().equals("7")) {
                            list.get(j).setRefuseReason("平台拒绝退款");
                        }
                        list.get(j).setRefund(Boolean.parseBoolean(list1.get(i).get("is_refund").toString()));
                    }
                }
            }
            for (int i = 0; i < list.size(); i++) {
                OdsOrder odsOrder = list.get(i);
                OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                odsOrderGoods.setOrderId(odsOrder.getOrderId());
                List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
                odsOrder.setOdsgoods(select);
                odsOrders.add(odsOrder);
            }

            pageInfo.setList(odsOrders);
            return WrapMapper.ok(pageInfo);
        }
        //已完成
        if (condition.equals("done")) {
            OdsOrder ods = new OdsOrder();
            ods.setOrderType((byte) 2);
            ods.setOrderStatus((byte) 2);
            ods.setShopId(Long.valueOf(shopid));
            PageHelper.startPage(page, size); // add by wg 20190403 增加分页查询
            list = odsOrderService.findbystatus(ods);
            PageInfo pageInfo = new PageInfo(list);
            PageHelper.startPage(0, 0); // add by wg 20190403 恢复
            for (int i = 0; i < list.size(); i++) {
                OdsOrder odsOrder = list.get(i);
                OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                odsOrderGoods.setOrderId(odsOrder.getOrderId());
                List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
                odsOrder.setOdsgoods(select);
                odsOrders.add(odsOrder);
            }

            pageInfo.setList(odsOrders);
            return WrapMapper.ok(pageInfo);
        }
        //已取消
        if (condition.equals("cancelled ")) {
            OdsOrder ods = new OdsOrder();
            ods.setOrderStatus((byte) 3);
            ods.setUserId(Long.valueOf(shopid));
            PageHelper.startPage(page, size); // add by wg 20190403 增加分页查询
            list = odsOrderService.findbystatus(ods);
            PageInfo pageInfo = new PageInfo(list);
            PageHelper.startPage(0, 0); // add by wg 20190403 恢复
            for (int i = 0; i < list.size(); i++) {
                OdsOrder odsOrder = list.get(i);
                OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
                odsOrderGoods.setOrderId(odsOrder.getOrderId());
                List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
                odsOrder.setOdsgoods(select);
                odsOrders.add(odsOrder);
            }

            pageInfo.setList(odsOrders);
            return WrapMapper.ok(pageInfo);
        }

        List<OdsOrder> tempList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo(tempList);
        return WrapMapper.ok(pageInfo);
//        return WrapMapper.ok(odsOrders);
    }


    @PostMapping("/orderId")
    @ApiOperation(httpMethod = "POST", value = "根据ID获取具体信息")
    public Wrapper<OrderBasicDto> orderDetail(@ApiParam(name = "odsOrder", value = "记录orderid") @RequestBody OdsOrder odsOrder) {

        if (odsOrder == null || odsOrder.getOrderId() == null){
            return WrapMapper.error("参数错误！");
        }

        odsOrder = odsOrderService.findById(odsOrder.getOrderId());
        if (odsOrder == null){
            return WrapMapper.error("未找到该订单！");
        }
        OrderBasicDto orderBasicDto = new OrderBasicDto();
        BeanUtils.copyProperties(odsOrder,orderBasicDto);

        List<OrderGoodsDto> list = odsOrderGoodsService.selectByOrderId(odsOrder.getOrderId());

        orderBasicDto.setOrderGoodsDtos(list);
        return WrapMapper.ok(orderBasicDto);
    }

    @PostMapping("/shopName")
    @ApiOperation(httpMethod = "POST", value = "根据ID获取具体信息")
    public Wrapper<PageInfo<OrderGoodsDto>> goodsDetailByshopName(@ApiParam(name = "shopName", value = "shopName") @RequestParam String shopName,
                                                        @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                        @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {

        if (shopName == null || shopName == ""){
            return WrapMapper.error("参数错误！");
        }
        System.out.println(shopName);
        List<ShopInfoDto> shopInfoDtos = smcFeignApi.getShopInfoByShopName(shopName);
        if (shopInfoDtos == null || shopInfoDtos.size() < 1){
            return WrapMapper.error("未找到店铺！");
        }
        List<Long> shopIds = shopInfoDtos.stream().map(ShopInfoDto::getShopId).collect(Collectors.toList());
        System.out.println("未找到店铺？" + shopIds);
        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("create_time desc");
        //criteria.andCondition("shipping_status > 1");
        criteria.andCondition("order_status < 3");
        criteria.andCondition("DATE_SUB(CURDATE(), INTERVAL 30 DAY) <=date(create_time)");
        criteria.andIn("shopId", shopIds);
        List<OdsOrder> odsOrderList = odsOrderService.selectByExample(example);
        if (odsOrderList == null || odsOrderList.size() < 1){
            return WrapMapper.error("未查找到订单数据");
        }
        List<Long> orderIds = odsOrderList.stream().map(OdsOrder::getOrderId).collect(Collectors.toList());

        PageHelper.startPage(page, size);
        List<OrderGoodsDto> list =  odsOrderGoodsService.selectOrderGoodsByShopIds(orderIds);

        for(OrderGoodsDto goods : list){
            for(ShopInfoDto shop : shopInfoDtos){
                if (goods.getShopId().equals(shop.getShopId())){
                    goods.setShopName(shop.getShopName());
                }
            }
        }

        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @PostMapping("/findOrderGoods")
    @ApiOperation(httpMethod = "POST", value = "获取订单及相关商品")
    public Wrapper<PageInfo<ShopOrderGoodsDto>> findOrderGoods(@ApiParam(name = "shopName", value = "shopName") @RequestBody ShopOrderGoodsDto shopOrderGoodsDto,
                                                           @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                           @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size

    ){
        PageHelper.startPage(page, size);

        List<ShopOrderGoodsDto> list = odsOrderService.findOrderGoods(shopOrderGoodsDto);

        PageInfo<ShopOrderGoodsDto> result = new PageInfo<>(list);

        return WrapMapper.ok(result);
    }

}
